//
//  WJAlertUtils.m
//  ChiShaNe
//
//  Created by 王军 on 16/3/25.
//  Copyright © 2016年 王军. All rights reserved.
//

#import "WJAlertUtils.h"
#import "WJAlertView.h"
#import "WJUIButton+Blocks.h"
#import <UIKit/UIKit.h>

#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"

#define SCREEN_WIDTH          ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT         ([UIScreen mainScreen].bounds.size.height)
#define SCREEN_WIDTH_VERTICAL          MIN(SCREEN_WIDTH,SCREEN_HEIGHT)
#define SCREEN_HEIGHT_VERTICAL          MAX(SCREEN_WIDTH,SCREEN_HEIGHT)


#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f \
alpha:(a)]
#define CGRGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1].CGColor
#define HEXCOLOR(hex) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:1]

#define HEXCOLORA(hex,p) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:p]


#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f \
alpha:(a)]


#define kDevice_Is_iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125,2436), [[UIScreen mainScreen] currentMode].size) : NO)


@implementation WJAlertUtils

+(void)alertMsg:(NSString *)msg vc:(UIViewController *)vc
{
    WJAlertView *alert = [[WJAlertView alloc]initWithTitle:@"提示" message:msg viewController:vc];
    RIButtonItem *okBtn = [RIButtonItem itemWithLabel:@"确定" action:^{
//        NSLog(@"确定按钮按下");
    }];
    [alert addButton:okBtn type:RIButtonItemType_Cancel];
    [alert show];
}

+(void)alertMsg:(NSString *)msg vc:(UIViewController *)vc action:(void(^)(void))action{
    WJAlertView *alert = [[WJAlertView alloc]initWithTitle:@"提示" message:msg viewController:vc];
    RIButtonItem *okBtn     = [RIButtonItem itemWithLabel:@"确定" action:action];
    [alert addButton:okBtn type:RIButtonItemType_Other];
    [alert show];
    
}

+(void)confirm:(NSString *)msg vc:(UIViewController *)vc
          btn1:(NSString *)b1txt action1:(void(^)(void))action1
          btn2:(NSString *)b2txt action2:(void(^)(void))action2{
    WJAlertView *alert = [[WJAlertView alloc]initWithTitle:@"提示" message:msg viewController:vc];
    RIButtonItem *okBtn     = [RIButtonItem itemWithLabel:b1txt action:action1];
    RIButtonItem *cancelBtn = [RIButtonItem itemWithLabel:b2txt action:action2];
    [alert addButton:okBtn type:RIButtonItemType_Other];
    [alert addButton:cancelBtn type:RIButtonItemType_Cancel];
    [alert show];
}


+(void)confirm:(NSString *)msg checkbox:(NSString *)msg2 vc:(UIViewController *)vc
          btn1:(NSString *)b1txt action1:(void(^)(void))action1
          btn2:(NSString *)b2txt action2:(void(^)(void))action2{
    WJAlertView *alert = [[WJAlertView alloc]initWithTitle:@"提示" message:msg viewController:vc];
    RIButtonItem *okBtn     = [RIButtonItem itemWithLabel:b1txt action:action1];
    RIButtonItem *cancelBtn = [RIButtonItem itemWithLabel:b2txt action:action2];
    [alert addButton:okBtn type:RIButtonItemType_Other];
    [alert addButton:cancelBtn type:RIButtonItemType_Cancel];
    [alert show];
}


+(void)actionSheet:(NSArray *)titles vc:(UIViewController *)vc action:(void(^)(int))action{
    WJAlertView *alert = [[WJAlertView alloc]initWithTitle:@"提示" message:@"" viewController:vc];
    NSUInteger len =titles.count;
    for (int i=0;i<len;i++) {
        NSString *title = [titles objectAtIndex:i];
        RIButtonItem *okBtn     = [RIButtonItem itemWithLabel:title action:^{
            action(i);
        }];
        [alert addButton:okBtn type:RIButtonItemType_Other];
    }
    [alert show];
}

+(void)actionSheet:(NSArray *)btnsTxt title:(NSString *)title msg:(NSString*)msg vc:(UIViewController *)vc action:(void(^)(int))action{
    WJAlertView *alert = [[WJAlertView alloc]initWithTitle:title message:msg viewController:vc];
    NSUInteger len =btnsTxt.count;
    for (int i=0;i<len;i++) {
        NSString *title = [btnsTxt objectAtIndex:i];
        RIButtonItem *okBtn  = [RIButtonItem itemWithLabel:title action:^{
            action(i);
        }];
        [alert addButton:okBtn type:RIButtonItemType_Other];
    }
    [alert show];
}

#define kActionSheetHeight  (44 * (SCREEN_WIDTH_VERTICAL/320.))
+(void)actionSheetBottom:(NSArray *)btnsTxt title:(NSString *)title msg:(NSString*)msg vc:(UIViewController *)vc action:(void(^)(int))action{
    UIView *showInView = vc.view;
    NSInteger maskViewTag =  0x882711;//遮罩的tag
    UIView *maskView = [showInView viewWithTag:maskViewTag];
    if(maskView){
        return;
    }else{
        maskView = [UIView new];
    }
    [showInView addSubview:maskView];
    maskView.tag = maskViewTag;
    maskView.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
    [maskView makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(showInView);
        make.height.equalTo(showInView);
        make.centerX.equalTo(showInView);
        make.centerY.equalTo(showInView);
    }];
    //放一堆按钮的界面
    WJUIButton_Blocks *cView = [[WJUIButton_Blocks alloc]initWithBlock:^{
        [maskView removeFromSuperview];
        [maskView setHidden:YES];
    }];
    [maskView addSubview:cView];
    cView.tag = maskViewTag+1;
    cView.backgroundColor = RGBACOLOR(0, 0, 0, 0);
    [cView makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(maskView);
        make.height.equalTo(maskView);
        make.centerX.equalTo(maskView);
        make.bottom.equalTo(maskView).offset(300);
    }];
    //然后是白色的框
    //最底下的是白的按钮
    WJUIButton_Blocks *cancelBtn = [[WJUIButton_Blocks alloc]initWithBlock:^{
        action(-999);
        [maskView removeFromSuperview];
    }];
    
//    [cancelBtn setSelected:YES];
    [cView addSubview:cancelBtn];
    [self renderWhitemBtn:cancelBtn];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:RGBCOLOR(249 ,119 ,119 ) forState:UIControlStateNormal];
    if (kDevice_Is_iPhoneX) {
        [cancelBtn makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(cView).offset(-10);
            make.height.equalTo(kActionSheetHeight);
            make.centerX.equalTo(cView);
            make.bottom.equalTo(cView).offset(-5-34);
        }];
    }else{
        [cancelBtn makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(cView).offset(-10);
            make.height.equalTo(kActionSheetHeight);
            make.centerX.equalTo(cView);
            make.bottom.equalTo(cView).offset(-5);
        }];
    }

    UIView *lastView = nil;
    //循环数组
    NSInteger cnt = btnsTxt.count;
    for (int i=0 ; i<cnt ; i++) {
        NSString *title = btnsTxt[i];
        WJUIButton_Blocks *itemBtn = [[WJUIButton_Blocks alloc]initWithBlock:^{
            action(i);
            [maskView removeFromSuperview];
        }];
        [cView addSubview:itemBtn];
        [itemBtn setBackgroundImage:[WJAlertUtils imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [itemBtn setBackgroundImage:[WJAlertUtils imageFromColor:RGBCOLOR(220, 220, 220)] forState:UIControlStateHighlighted];
        [itemBtn setTitleColor:HEXCOLOR(0x139ffC) forState:UIControlStateNormal];
        itemBtn.titleLabel.font = [UIFont systemFontOfSize:16.];
        CGFloat topOffset = 0.5;
        [itemBtn setTitle:title forState:UIControlStateNormal];
        if (lastView) {
            [itemBtn makeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(cView).offset(-10);
                make.height.equalTo(kActionSheetHeight);
                make.centerX.equalTo(cView);
                make.top.equalTo(lastView.bottom).offset(topOffset);
            }];
        }else{
            CGFloat sumH = kActionSheetHeight+11+(0.5+kActionSheetHeight) * cnt;
            if (kDevice_Is_iPhoneX) {
                [itemBtn makeConstraints:^(MASConstraintMaker *make) {
                    make.width.equalTo(cView).offset(-10);
                    make.height.equalTo(kActionSheetHeight);
                    make.centerX.equalTo(cView);
                    make.top.equalTo(cView.bottom).offset(-sumH-34);
                }];
            }else{
                [itemBtn makeConstraints:^(MASConstraintMaker *make) {
                    make.width.equalTo(cView).offset(-10);
                    make.height.equalTo(kActionSheetHeight);
                    make.centerX.equalTo(cView);
                    make.top.equalTo(cView.bottom).offset(-sumH);
                }];
            }
        }
        [itemBtn layoutIfNeeded];
        if (i == 0 && cnt == 1)
        {//只有一项,全部圆角
             [self btnCornerRadius:itemBtn byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight|UIRectCornerBottomLeft | UIRectCornerBottomRight ];
        }
        else if (i==0) {
            [self btnCornerRadius:itemBtn byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight ];
        }else if (i==cnt-1){
             [self btnCornerRadius:itemBtn byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight ];
        }else{
            
        }
        lastView = itemBtn;
    }
    //动画
    [maskView layoutIfNeeded];
    [maskView setNeedsUpdateConstraints];
    [maskView updateConstraintsIfNeeded];
    [UIView animateWithDuration:0.2 animations:^{
        [cView updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(maskView).offset(0);
        }];
        [maskView layoutIfNeeded];
    } completion:^(BOOL finished) {
       
    }];
}

+(void)renderWhitemBtn:(UIButton *)btn{
    [btn setBackgroundImage:[WJAlertUtils imageFromColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [btn setBackgroundImage:[WJAlertUtils imageFromColor:RGBCOLOR(220, 220, 220)] forState:UIControlStateHighlighted];
    [btn setTitleColor:HEXCOLOR(0x139ffC) forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16.];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 8;
}

//[self btnCornerRadius:btn byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRigh]
+(void)btnCornerRadius:(UIButton *)btn byRoundingCorners:(UIRectCorner)corners{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:btn.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(8, 8)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = btn.bounds;
    maskLayer.path = maskPath.CGPath;
    btn.layer.mask = maskLayer;
}

//弹出框,返回的是遮罩，关闭时dismiss就行
+(UIView *)commonPopView:(UIView *)showView vc:(UIViewController *)vc {
    UIView *showInView = vc.view;
    NSInteger maskViewTag =  0x882711;//遮罩的tag
    UIView *maskView = [UIView new];
    [showInView addSubview:maskView];
    maskView.tag = maskViewTag;
    maskView.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
    [maskView makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(showInView);
        make.height.equalTo(showInView);
        make.centerX.equalTo(showInView);
        make.centerY.equalTo(showInView);
    }];
    //放一堆按钮的界面
//    UIView *cView = [UIView new];
    WJUIButton_Blocks *cView = [[WJUIButton_Blocks alloc]initWithBlock:^{
        if ([WJAlertUtils keyboardMaybeShow:maskView]) {
            [WJAlertUtils closeKeyboard];
        }else{
            [UIView animateWithDuration:0.4 animations:^{
                maskView.alpha = 0.1;
            } completion:^(BOOL finished) {
                [maskView removeFromSuperview];
                [maskView setHidden:YES];
            }];
        }
    }];
    [maskView addSubview:cView];
    cView.tag = maskViewTag+1;
    cView.backgroundColor = RGBACOLOR(0, 0, 0, 0);
    [cView makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(maskView);
        make.height.equalTo(maskView);
        make.centerX.equalTo(maskView);
        make.bottom.equalTo(maskView).offset(300);
    }];
   //
    [cView addSubview:showView];
    [showView makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(cView);
    }];
    //动画
    [maskView layoutIfNeeded];
    [maskView setNeedsUpdateConstraints];
    [maskView updateConstraintsIfNeeded];
    [UIView animateWithDuration:0.2 animations:^{
        [cView updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(maskView).offset(0);
        }];
        [maskView layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
    return maskView;
}

+ (UIImage *) imageFromColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
//键盘是否打开状态（可能不准）
+(BOOL)keyboardMaybeShow:(UIView *)view{
    //拿到这个view上面的第一响应对象
    if (view.isFirstResponder)
    {
        [view resignFirstResponder];
        return YES;
    }
    for (UIView* subView in view.subviews)
    {
        if ( [WJAlertUtils keyboardMaybeShow:subView])
            return YES;
    }
    return NO;
}


+(void)closeKeyboard{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}


@end
